<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--表格部分-->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border style="width: 100%" stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1===0 ? 'bdtop':'', 'vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!--一级菜单-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--二级菜单和三级菜单-->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '':'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!--2级菜单-->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--3级菜单-->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色对话框-->
    <el-dialog title="添加角色" width="50%" :visible.sync="addDialogVisible" @close="addDialogClose">
      <!--添加角色表单-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改角色对话框-->
    <el-dialog title="修改角色" width="50%" :visible.sync="editDialogVisible" @close="editDialogClose">
      <!--修改角色表单-->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配角色对话框-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="closeRightDialog">
      <!--树形菜单区域-->
      <el-tree
      :data="righttree"
      show-checkbox node-key="id"
      :props="treeProps"
      default-expand-all
      :default-checked-keys="checkedKeys"
      ref="rightRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRightDialog">取 消</el-button>
        <el-button type="primary" @click="addRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      addDialogVisible: false,
      // 表单的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 255,
            message: '长度在 255 个字符以内',
            trigger: 'blur'
          }
        ]
      },
      // 添加角色表单
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改表单的验证规则对象
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 255,
            message: '长度在 255 个字符以内',
            trigger: 'blur'
          }
        ]
      },
      // 修改角色表单数据
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      editDialogVisible: false,
      setRightDialogVisible: false,
      righttree: {},
      // 树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 加载已选中的树
      checkedKeys: [],
      checkRoleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addRole() {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res && res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        // 关闭对话框
        this.addDialogVisible = false
        // 刷新列表
        this.getRoleList()
        this.$message.success(res.meta.msg)
      })
    },
    // 角色修改部分
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    editRoleInfo() {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) {
          return
        }
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        )
        if (res && res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getRoleList()
        this.$message.success(res.meta.msg)
      })
    },
    // 删除角色操作
    async removeRoleById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了该操作')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 刷新列表
      this.getRoleList()
      this.$message.success(res.meta.msg)
    },
    // 删除角色的权限
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色的此权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了该操作')
      }
      const { data: res } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + id
      )
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 刷新列表
      // this.getRoleList()
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 给角色分配权限
    async showSetRightDialog(row) {
      this.checkedKeys = []
      // 获取所有权限
      const { data: res } = await this.$http.get('rights/tree')
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.righttree = res.data
      this.getLeafKeys(row, this.checkedKeys)
      this.setRightDialogVisible = true
      this.checkRoleId = row.id
    },
    // 通过递归获取角色下所有三级节点的id，并保存到数组checkedKeys中
    getLeafKeys(node, arr) {
      if (!node.children) {
        arr.push(node.id)
        return
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    closeRightDialog() {
      this.setRightDialogVisible = false
      this.checkedKeys = []
    },
    async addRights() {
      const cks = [
        ...this.$refs.rightRef.getHalfCheckedKeys(),
        ...this.$refs.rightRef.getCheckedKeys()
      ]
      if (cks.length === 0) {
        return this.$message.warning('请选择需要授予的权限！')
      }
      const idStr = cks.join(',')
      const { data: res } = await this.$http.post('roles/' + this.checkRoleId + '/rights', { rids: idStr })
      if (res && res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
